package com.fsh.anime.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fsh.anime.common.PartyConstant;
import com.fsh.anime.mapper.PartyContentMapper;
import com.fsh.anime.mapper.PartyInfoMapper;
import com.fsh.anime.minio.FileStorageService;
import com.fsh.anime.model.dtos.PartyAllDto;
import com.fsh.anime.model.dtos.PartyQueryDto;
import com.fsh.anime.model.pojos.ArticleCover;
import com.fsh.anime.model.pojos.PartyContent;
import com.fsh.anime.model.pojos.PartyInfo;
import com.fsh.anime.model.vos.PageResult;
import com.fsh.anime.model.vos.Result;
import com.fsh.anime.service.PartyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.HtmlUtils;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class PartyServiceImpl extends ServiceImpl<PartyInfoMapper, PartyInfo> implements PartyService {
    @Autowired
    private PartyInfoMapper partyInfoMapper;
    @Autowired
    private PartyContentMapper partyContentMapper;
    @Autowired
    private FileStorageService fileStorageService;

    //---------------后台--------------


    /**
     * 分页获取漫展列表
     *
     */
    @Override
    public Result getPartiesForBack(PartyQueryDto dto) {
        IPage page=new Page(dto.getCurrentPage(),PartyConstant.PAGE_SIZE);
        IPage page1 = partyInfoMapper.selectPage(page, new QueryWrapper<PartyInfo>()
                .orderByDesc("show_date"));
        PageResult pageResult=new PageResult();
        pageResult.setRecords(page1.getRecords());
        pageResult.setTotal(page1.getTotal());
        return Result.success(pageResult);
    }

    /**
     * 后台添加漫展活动
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addPartyShow(PartyAllDto partyAllDto) {
        //编辑
        if (partyAllDto.getId()!=null){
            //删除记录再新增  todo 后续换上更新，而不是删除再新增
            partyInfoMapper.deleteById(partyAllDto.getId());
            partyContentMapper.delete(new QueryWrapper<PartyContent>().eq("info_id",partyAllDto.getId()));
        }
        //先插入party_info表中
        PartyInfo partyInfo=new PartyInfo();
        BeanUtils.copyProperties(partyAllDto,partyInfo);
        LocalDateTime localDateTime = LocalDateTime.parse(partyAllDto.getShowDate(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        partyInfo.setShowDate(localDateTime);
        partyInfo.setState(PartyConstant.NORMAL);
//        System.out.println(partyInfo);
        int insert1 = partyInfoMapper.insert(partyInfo);

        //插入party_content表
        PartyContent partyContent=new PartyContent();
        partyContent.setInfoId(partyInfo.getId());
        partyContent.setContent(HtmlUtils.htmlEscapeHex(partyAllDto.getContent()));
        int insert2 = partyContentMapper.insert(partyContent);

        if(insert1+insert2>1){
            return Result.success("注册成功");
        }
        return Result.error("注册失败");
    }

    /**
     * 后台查询漫展活动
     */
    @Override
    public Result queryBystateAndTitle(PartyQueryDto dto) {
        IPage page=new Page(dto.getCurrentPage(),PartyConstant.PAGE_SIZE);
        //构建查询条件
        QueryWrapper<PartyInfo> queryWrapper = new QueryWrapper<PartyInfo>()
                .like(StringUtils.isNotBlank(dto.getTitle()), "title", dto.getTitle())
                .orderByDesc("show_Date");
        if(StringUtils.isNotBlank(dto.getState()) && !"全部".equals(dto.getState())){
            queryWrapper.eq(dto.getState() != null, "state", dto.getState());
        }
        //查询
        IPage page1 = partyInfoMapper.selectPage(page, queryWrapper);
        PageResult pageResult=new PageResult();
        pageResult.setTotal(page1.getTotal());
        pageResult.setRecords(page1.getRecords());
        return Result.success(pageResult);
    }

    /**
     * 上传漫展 封面 的图片
     *
     * @param file
     */
    @Override
    public String uploadImg(MultipartFile file) {
        //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件的扩展名（截取字符串）
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //用uuid构造新的文件名+扩展名
        String newFileName= UUID.randomUUID().toString()+extension;
//        System.out.println(newFileName);
        String imgPath=null;
        InputStream is = null;
        //上传图片到minio
        try {
            is = file.getInputStream();
            imgPath = fileStorageService.uploadImgFile("", newFileName,is);
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败";
        }finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return imgPath;
    }

    // -----------------前台-------------------

    /**
     * 前台分页获取漫展列表
     */
    @Override
    public Result getParties( PartyQueryDto dto) {
        IPage page=new Page(dto.getCurrentPage(),PartyConstant.PAGE_SIZE);
        IPage page1 = partyInfoMapper.selectPage(page, new QueryWrapper<PartyInfo>()
                .eq("state", "正常")
                .like(StringUtils.isNotBlank(dto.getKeyword()), "title", dto.getKeyword())
                .orderByAsc("show_date"));
        PageResult pageResult=new PageResult();
        pageResult.setRecords(page1.getRecords());
        pageResult.setTotal(page1.getTotal());
        return Result.success(pageResult);
    }

    /**
     * 获取某个漫展内容详情
     */
    @Override
    public Result getPartyContent(String id) {
        PartyContent partyContent = partyContentMapper.selectOne(new QueryWrapper<PartyContent>().eq("info_id", id));
        String content = HtmlUtils.htmlUnescape(partyContent.getContent());
        return Result.success(content);
    }

    /**
     * 获取某个漫展详情
     *
     * @param id
     */
    @Override
    public Result getPartyInfo(String id) {
        PartyInfo partyInfo = partyInfoMapper.selectById(id);
        return Result.success(partyInfo);
    }
}
